﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using VirtualKeyboard.Contract;
using VirtualKeyboard.Service.Commands;
using VirtualKeyboard.Service.TcpServices;

namespace VirtualKeyboard.Service
{
    public class KeyMethodHandler : ITcpContextHandler
    {
        private readonly Regex regex;
        private const string Pattern = @"([\w\d]*)\.([\w\d]*)";

        private readonly KeyboardCommand keyboardCommand;
        private readonly MediaCommand mediaCommand;

        public KeyMethodHandler()
        {
            regex = new Regex(Pattern, RegexOptions.Singleline | RegexOptions.Compiled);
            keyboardCommand = new KeyboardCommand(KeyBoardHook.Instance);
            mediaCommand = new MediaCommand(KeyBoardHook.Instance);
        }

        protected virtual void Visitor(string method)
        {
            var match = regex.Match(method);
            if (!match.Success) return;

            var methodType = match.Result("$1");
            methodType = VisitorMethod(methodType);
            var action = match.Result("$2");
            switch (methodType)
            {
                case KeyMethods.KeyboardPackage:
                    action = VisitorKeyboard(method, action);
                    break;
                case KeyMethods.MediaPackage:
                    action = VisitorMedia(method, action);
                    break;
                default: return;
            }
        }

        protected virtual string VisitorMethod(string method)
        {
            return method;
        }

        protected virtual string VisitorMedia(string method, string action)
        {
            mediaCommand.Press(method);
            return method;
        }

        protected virtual string VisitorKeyboard(string method, string action)
        {
            keyboardCommand.Press(action);
            return method;
        }

        public void ProcessRequest(TcpContext context)
        {
            Visitor(context.Request.Context);
        }
    }
}
